package org.fedex.rg.async;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.fedex.rg.async.callbacks.PlaylistUpdateFinishedListener;
import org.fedex.rg.model.Song;
import org.fedex.rg.servises.PlaylistUpdateService;
import org.fedex.rg.utils.Log;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

public class UpdatePlaylistTask extends AsyncTask<Void, String, List<Song>> {

	private PlaylistUpdateService mPlaylistUpdateService;
	private PlaylistUpdateFinishedListener listener;

	private Context mContext;
	private ProgressDialog mProgressDialog;

	public UpdatePlaylistTask(Context context,
			PlaylistUpdateService mPlaylistUpdateService,
			PlaylistUpdateFinishedListener listener) {
		super();
		this.mContext = context;
		this.mPlaylistUpdateService = mPlaylistUpdateService;
		this.listener = listener;
	}

	@Override
	protected void onPreExecute() {
		mProgressDialog = ProgressDialog.show(mContext, "Please wait...",
				"Retrieving data ...", true);
		super.onPreExecute();
	}

	@Override
	protected List<Song> doInBackground(Void... params) {
		List<Song> songs = null;
		try {
			songs = mPlaylistUpdateService.updatePlaylist();
		} catch (IOException e) {
			Log.e(e.getMessage());
		}
		return (songs == null) ? new ArrayList<Song>() : songs;
	}

	@Override
	protected void onPostExecute(List<Song> result) {
		mProgressDialog.dismiss();
		listener.onUpdateFinish(result);
		super.onPostExecute(result);
	}

}
